package com.my.demo.shiro.realms;

import com.my.demo.utils.DesUtil;
import com.my.demo.shiro.token.SmsToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author liangyuanshao
 * @date 2021/12/22 - 20:19
 */
public class SmsRealm extends AuthorizingRealm {

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof SmsToken;
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    return null;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {

    SmsToken smsToken= (SmsToken) token;
    String phone = (String) smsToken.getPrincipal();
    String sms = (String) smsToken.getCredentials();
    String userToken=smsToken.getToken();
    SimpleAuthenticationInfo simpleAuthenticationInfo;
    if(DesUtil.getDecryptString(userToken).equals(phone+sms)){
       simpleAuthenticationInfo = new SimpleAuthenticationInfo(phone,sms,this.getName());
    }else {
      throw new IncorrectCredentialsException();
    }



    return simpleAuthenticationInfo;
  }
}
